package cn.base.web.authc;

import cn.rengy.auth.Authentication;
import cn.rengy.auth.AuthenToken;
import cn.rengy.auth.Authenticator;
import cn.rengy.auth.exception.AuthException;
import cn.rengy.auth.realm.Realm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class DefaultAuthenticator implements Authenticator {

    @Autowired
    private List<Realm> realms;
    @Override
    public Authentication authenticate(AuthenToken authenticationToken) throws AuthException {
        Authentication info = null;
        for (Realm realm : realms) {
            if (realm.supports(authenticationToken)) {
                log.debug("Matching realm, [{}] support token [{}].", realm.getName(), authenticationToken);
                info = realm.getAuthenticationInfo(authenticationToken);
                return info;
            } else {
                log.debug("Skipping realm, [{}] does not support token [{}].", realm.getName(), authenticationToken);
            }
        }
        throw new AuthException(401,"All realm auth fail.");
    }

    private void onLoginSuccess(){

    }
}
